package asynqQueueWorker

import (
	"context"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gookit/event"
	"github.com/hibiken/asynq"
	"seawolf-admin-go/internal/consts"
	"seawolf-admin-go/utility/asynq/asynqQueue"
)

func getAsynqHandleFunc(ctx context.Context, topic asynqQueue.WorkflowTopicType) asynq.HandlerFunc {
	switch topic {
	case asynqQueue.UserConfirmScore:
		return func(tctx context.Context, task *asynq.Task) error {
			// 实际处理

			return nil
		}
	default: // 默认处理，使用eventBus
		return func(ctx context.Context, task *asynq.Task) error {
			json, err := gjson.DecodeToJson(task.Payload())
			if err != nil {
				return err
			}
			// 触发全局eventBus
			err, _ = event.Trigger(consts.AsynqEventProfix+asynqQueue.WorkflowTopicName[topic], json.Map())
			if err != nil {
				return err
			}
			return nil
		}
	}
}

// InitTopic 初始化任务
func InitTopic(ctx context.Context, topics ...asynqQueue.WorkflowTopicType) {
	srv := asynq.NewServer(
		asynqQueue.GetRedisClientOpt(ctx),
		asynq.Config{
			Concurrency: 10, // 并发数
		},
	)
	mux := asynq.NewServeMux()
	// 注册任务
	for _, topic := range topics {
		mux.HandleFunc(asynqQueue.WorkflowTopicName[topic], getAsynqHandleFunc(ctx, topic))
	}
	go srv.Run(mux)
}
